package com.jnshu.filter;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static org.springframework.http.HttpHeaders.ORIGIN;

/**
 * @author Martin
 * @date 2019/8/17 14:06
 * 跨域过滤器
 * CORS Filter是适用于支持Java web应用跨源资源共享（CORS）的首个统一解决方案。
 * 而跨源资源共享（CORS）是W3C近期一直致力于引入的保障从web浏览器到处理请求的服务器之间跨域请求的标准化机制。
 * 详情参考：https://www.cnblogs.com/sloong/p/cors.html
 */
public class CorsFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        request.getHeader(ORIGIN);
        response.setHeader ("Access-Control-Allow-Origin", "*");//* or origin as u prefer
        response.setHeader ("Access-Control-Allow-Credentials", "true");
        response.setHeader ("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE");
        response.setHeader ("Access-Control-Max-Age", "360000");
        response.setHeader ("Access-Control-Allow-Headers", "content-type, authorization");
        response.setHeader ("Access-Control-Expose-Headers", "Authorization");

        if (request.getMethod ().equals ("OPTIONS")) {
            response.setStatus (HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter (request, response);
        }
    }
}
